package com.sias.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionManager;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * @author 吴文杰
 * @version 1.0
 * @since 2023/5/31 11:36
 */
@Configuration
@ComponentScan("com.sias.service")
@MapperScan("com.sias.mapper")
@EnableTransactionManagement
@PropertySource("classpath:jdbc.properties")
public class SpringConfig {

  @Autowired
  Environment env;

  @Bean
  public DataSource dataSource(){
    DruidDataSource dataSource = new DruidDataSource();
    dataSource.setDriverClassName(env.getProperty("jdbc.driver"));
    dataSource.setUrl(env.getProperty("jdbc.url"));
    dataSource.setUsername(env.getProperty("jdbc.username"));
    dataSource.setPassword(env.getProperty("jdbc.password"));
    return dataSource;
  }

  @Bean
  public SqlSessionFactoryBean sqlSessionFactory() throws IOException {
    SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Resource[] resource = resolver.getResources("classpath:mapper/*.xml");
    sessionFactoryBean.setMapperLocations(resource);
    sessionFactoryBean.setTypeAliasesPackage("com.sias.domain");
    sessionFactoryBean.setDataSource(dataSource());
    return sessionFactoryBean;
  }

}
